package com.xfzp.android.ms;

import com.xfzp.d3.Coord;

/**
 * 
 * @author AndroidApe
 * @version 2011-12-5
 */
public class AbleLayer {
	private int layerId;
	private boolean back;// 选择的是否是背面。如果是背面，则层转动的方向将与拖动的方向相反

	private float remainAngle;// 可转动的角度
	private float hasAngle;// 当前层已转动的角度，取值范围-90~90
	private final float autoSpeed = 5;
	private boolean auto = false;

	public AbleLayer(int layerId, boolean back) {
		this.layerId = layerId;
		this.back = back;
	}

	/**
	 * 返回选择的层
	 * 
	 * @return
	 */
	public int getLayerId() {
		return layerId;
	}

	/**
	 * 设置自动旋转
	 */
	public void setAuto() {
		auto = true;
	}

	/**
	 * 
	 * @return
	 */
	public float nextRotateAngle() {
		if (remainAngle != 0) {
			float a = remainAngle;
			hasAngle += a;
			remainAngle -= a;
			return a;
		} else if (auto) {
			if (hasAngle != 0) {
				float a = Math.abs(hasAngle);
				if (a < 35) {
					a = -Math.min(a, autoSpeed);
				} else {
					a = Math.min(90 - a, autoSpeed);
				}
				if (hasAngle < 0) {
					a = -a;
				}
				hasAngle += a;
				return a;
			} else {
				auto = false;
			}
		}
		return 0;
	}

	/**
	 * 重新计算已旋转的角度
	 * 
	 * @return
	 */
	public int resumeHasRotateAngle() {
		int i = 0;
		while (hasAngle >= 90) {
			i++;
			hasAngle -= 90;
		}
		while (hasAngle <= -90) {
			i--;
			hasAngle += 90;
		}
		return i;
	}

	/**
	 * 计算移动距离对应的旋转角度
	 * 
	 * @param dir
	 * @return
	 */
	public void rotateAngle(Coord dir) {
		float angle = 0;
		if (layerId < 3) {// 绕X轴旋转的层
			angle = Math.abs(dir.y()) > Math.abs(dir.z()) ? -dir.y() : dir.z();
		} else if (layerId < 6) {// 绕Y轴旋转的层
			angle = Math.abs(dir.x()) > Math.abs(dir.z()) ? dir.x() : -dir.z();
		} else {// 绕Z轴旋转的层
			angle = Math.abs(dir.x()) > Math.abs(dir.y()) ? -dir.x() : dir.y();
		}
		angle *= 60;
		if (back)
			angle = -angle;
		remainAngle += angle;
	}
}
